import { GoodsType, Goods, GoodsSku } from '../model/goods';
import { ValidateRule, validate } from '../utils/validate';

/**
 * [API] 获取商品和活动信息
 */
export interface ServiceGoodsGetGoodsAndPromotionParams {
  goods_id: number;
  shop_id?: number;
  promotion_type: string;
}

/**
 * [API] 获取商品
 */
export interface ServiceGoodsGetParams {
  // 主键ID 如果传入ID则只返回一个项目
  id?: number;
  currentPage?: number;
  pageSize?: number;
  /**
   * 是否返回总量统计
   */
  count?: boolean;
  filter?: {
    id?: number;
    shop?: number;
    is_display?: 1 | 0;
    type?: GoodsType;
    /** 后加的暂时只是前端用来储存，实际请求时还是使用下下面的 tags */
    tags?: number[];
  };
  tags?: number[] | string;
  sort?: boolean;
  field?: string;
  keywords?: string;
  shop_id?: number;
}

/**
 * 【校验规则】发布会员卡
 */
export const RuleGoodsPut: ValidateRule<Goods> = {
  title: [
    { required: true, message: '请填写商品名称' },
    { max: 40, message: '商品名称不得超过40个字' },
  ],
  images: {
    required: true,
    message: '请至少上传一张商品图片',
  },
  price: [
    {
      required: true,
      message: '请填写商品价格',
    },
    {
      type: 'price',
      allowEmpty: false,
      message: '请填写正确的商品价格',
    },
  ],
  quantity: {
    type: 'number',
    message: '请输入正确的库存数量',
  },
  // 限制必须输入时间 暂时没启用
  start_at: [
    {
      required: true,
      message: '请选择开售时间',
      enable: (values) => values.auto_listing_time === 1,
    },
  ],
  skus: {
    validator: (rule, value, cb, source) => {
      let { skus } = source;
      let e: any;
      if (typeof skus === 'object') {
        skus?.forEach((sku, index) => {
          validate<GoodsSku>(
            sku,
            {
              price: {
                required: true,
                type: 'price',
                allowEmpty: false,
                message: '请检查规格的价格',
              },
              quantity: {
                type: 'number',
                required: true,
                message: '请输入正确的规格库存数量',
              },
            },
            (_e) => {
              if (_e) e = _e;
            },
          );
        });
      }
      if (e) {
        return cb(e.message);
      }
      cb();
    },
  },
};
